package com.EAsystem.aop;

import com.EAsystem.utils.DateTimeUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 时间自动填充切面
 * 用于在方法执行前自动填充实体类的创建时间和更新时间
 */
@Aspect
@Component
public class TimeAutoFillAspect {

    /**
     * 在标记了 @AutoFillTime 注解的方法执行前，自动填充时间字段
     * 针对service层的方法进行拦截
     */
    @Before("@annotation(com.EAsystem.aop.AutoFillTime) && execution(* com.EAsystem.service..*.*(..))")
    public void autoFillTime(JoinPoint joinPoint) {
        // 获取目标方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取方法上的AutoFillTime注解
        AutoFillTime autoFillTime = method.getAnnotation(AutoFillTime.class);

        String currentTimeStr = DateTimeUtil.getCurrentTime();
        Date currentTimeDate = new Date();

        Object[] args = joinPoint.getArgs();

        for (Object arg : args) {
            if (arg != null) {
                try {

                    if (autoFillTime.createTime()) {
                        try {
                            Method setCreateTimeMethod = arg.getClass().getMethod("setCreateTime", Date.class);
                            setCreateTimeMethod.invoke(arg, currentTimeDate);
                        } catch (NoSuchMethodException e) {
                            try {
                                Method setCreateTimeMethod = arg.getClass().getMethod("setCreateTime", String.class);
                                setCreateTimeMethod.invoke(arg, currentTimeStr);
                            } catch (Exception ex) {
                            }
                        }
                    }

                    if (autoFillTime.updateTime()) {

                        try {
                            Method setUpdateTimeMethod = arg.getClass().getMethod("setUpdateTime", Date.class);
                            setUpdateTimeMethod.invoke(arg, currentTimeDate);
                        } catch (NoSuchMethodException e) {
                            try {
                                Method setUpdateTimeMethod = arg.getClass().getMethod("setUpdateTime", String.class);
                                setUpdateTimeMethod.invoke(arg, currentTimeStr);
                            } catch (Exception ex) {

                            }
                        }
                    }
                } catch (Exception e) {
                    continue;
                }
            }
        }
    }
}